﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OpenPhotoAlbum.DbAccess;
using OpenPhotoAlbum.Controls;

namespace OpenPhotoAlbum.BusinessLogics
{
	public class OwnerCache
	{
		#region Singleton

		private OwnerCache() { }

		private static readonly OwnerCache _instance = new OwnerCache();

		public static OwnerCache Instance
		{
			get { return _instance; }
		}

		static OwnerCache() { }

		#endregion

		private static readonly Guid SaltUser = Guid.NewGuid();

		public User GetUser(Guid userId)
		{
			Guid cacheKey = GuidUtility.Combine(userId, SaltUser);

			User user = null;

			if (CacheManager.Instance.ContainsKey(cacheKey))
			{
				user = CacheManager.Instance.ReadCache<User>(cacheKey);
			}
			else
			{
				user = UserManager.Instance.GetUser(userId);
				CacheManager.Instance.WriteCache<User>(cacheKey, user);
			}

			return user;
		}

		private static readonly Guid SaltAlbumOwner = Guid.NewGuid();

		public User GetAlbumOwner(Guid albumId)
		{
			Guid cacheKey = GuidUtility.Combine(albumId, SaltAlbumOwner);

			User user = null;

			if (CacheManager.Instance.ContainsKey(cacheKey))
			{
				user = CacheManager.Instance.ReadCache<User>(cacheKey);
			}
			else
			{
				user = AlbumManager.Instance.GetUser(albumId);
				CacheManager.Instance.WriteCache<User>(cacheKey, user);
			}

			return user;
		}

		private static readonly Guid SaltPhotoOwner = Guid.NewGuid();

		public User GetPhotoOwner(Guid photoId)
		{
			Guid cacheKey = GuidUtility.Combine(photoId, SaltPhotoOwner);

			User user = null;

			if (CacheManager.Instance.ContainsKey(cacheKey))
			{
				user = CacheManager.Instance.ReadCache<User>(cacheKey);
			}
			else
			{
				user = PhotoManager.Instance.GetUser(photoId);
				CacheManager.Instance.WriteCache<User>(cacheKey, user);
			}

			return user;
		}
	}
}
